import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_heating/common/app.dart';
import 'package:flutter_smart_heating/config/config.dart';
import 'package:flutter_smart_heating/ui/src/permission.dart';
import 'package:flutter_smart_heating/ui/ui.dart';
import 'package:get/get.dart';
import 'package:scan/scan.dart';
import 'widget/result.dart';

class QrcodeHandle {
  /// 图片识别
  static Future<bool> gallery(context) async {
    bool hasPermission = await UiPeromission.check(
      context,
      title: "识别图片中的二维码需要调用以下权限",
      permissions: [
        UiPermissionData(
          '读取相册',
          Permission.photos,
          onlyIOS: true,
        ),
        UiPermissionData(
          '读取相片/文件',
          Permission.manageExternalStorage,
          onlyAndroid: true,
        )
      ],
    );
    if (!hasPermission) {
      return true;
    }
    FilePickerResult? file =
        await FilePicker.platform.pickFiles(type: FileType.image);
    if (file != null) {
      await 0.3.delay();
      var result = await Scan.parse(file.files.first.path!);
      if (result != null) {
        await resolve(result);
        return false;
      } else {
        Ui.toast("识别失败");
      }
    }
    return true;
  }

  static Future<bool> resolve(result) async {
    App.hapticFeedback();

    if (result.startsWith('http')) {
      if (result
          .toString()
          .replaceFirst('http://', 'https://')
          .startsWith('${Config.server}/authorized/login/')) {
        await App.push(
          '/authorized/login?qrcode=$result&--token--',
          redirect: true,
        );
      } else {
        await App.push(result, redirect: true);
      }
      return true;
    } else {
      await showDialog(
        context: Get.context!,
        builder: (context) => Center(
          child: Container(
            margin: const EdgeInsets.all(20),
            width: double.infinity,
            height: 400,
            clipBehavior: Clip.hardEdge,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(15),
            ),
            child: QrcodeResultView(text: result),
          ),
        ),
      );
    }
    return false;
  }
}
